package com.niiwoo.civet.trade.listener.credit;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.trade.constant.LoanFlowMqConstant;
import com.niiwoo.civet.trade.service.loan.credit.CreditAmountDubboService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * 授信模型监听
 * Created by dell on 2018/4/19.
 * Description：civet-app
 */
@Slf4j
@Component
public class CreditModelListener {

    @Reference(version = "1.0.0")
    private CreditAmountDubboService creditAmountDubboService;

    /**
     * 额度评分卡（调用天秤获取授信额度）
     * @param message
     * @param channel
     */
    @RabbitListener(queues = {LoanFlowMqConstant.Queue.LOAN_LIMIT_SCORE_QUEUE})
    public void getCreditAmount(Message message, Channel channel) {
        String reqMsg = new String(message.getBody(), Charset.forName("UTF-8"));
        Long flowExecuteId = JSON.parseObject(reqMsg).getLong("flowExecuteId");
        log.info("【流程——额度评分卡】,flowExecuteId={}", flowExecuteId);
        try {
            creditAmountDubboService.getCreditAmount(flowExecuteId);
        } catch (Exception ex){
            log.error("【流程——额度评分卡】消费异常, flowExecuteId={}, message={}", flowExecuteId, JSON.toJSONString(message), ex);
        } finally {
            doAckAnswer(message, channel);
        }
    }

    /**
     * 借款提额额度评分卡（调用天秤获取授信额度）
     * @param message
     * @param channel
     */
    @RabbitListener(queues = {LoanFlowMqConstant.Queue.LOAN_TE_LIMIT_SCORE_QUEUE})
    public void getTeCreditAmount(Message message, Channel channel) {
        String reqMsg = new String(message.getBody(), Charset.forName("UTF-8"));
        Long flowExecuteId = JSON.parseObject(reqMsg).getLong("flowExecuteId");
        log.info("【流程——提额额度评分卡】,flowExecuteId={}", flowExecuteId);
        try {
            creditAmountDubboService.getTeCditAmount(flowExecuteId);
        } catch (Exception ex){
            log.error("【流程——提额额度评分卡】消费异常, flowExecuteId={}, message={}", flowExecuteId, JSON.toJSONString(message), ex);
        } finally {
            doAckAnswer(message, channel);
        }
    }


    /**
     * 确认消息已经接收
     * @param message
     * @param channel
     */
    private void doAckAnswer(Message message, Channel channel) {
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException ie) {
            log.error("credit model ack occur exception, the reason is : {}", ie);
        }
    }

}
